﻿using System;
using FlowCanvas;
using FlowCanvas.Nodes;
using LogSystem;
using NodeCanvas.Framework;
using ParadoxNotion;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class CounterEvent : EventNode
    {
        public static Action<string, int> OnCounterValueChanged;

        [RequiredField]
        public BBParameter<string> counterName;
        public BBParameter<int> triggerValue = 1;
        
        private BlueprintCounter _blueprintCounter;

        private FlowOutput onEnd;
        private FlowOutput onUpdate;
        
        public override string name
        {
            get
            {
                return string.Format("{0} ({1})", "Counter", counterName.value);
            }
        }
        
        protected override void RegisterPorts()
        {
            AddFlowInput("start",OnStart);
            onEnd = AddFlowOutput("End");
            onUpdate = AddFlowOutput("Update");
            
            AddValueOutput<int>("count", () => { return _blueprintCounter.Count; });
        }
        
        public void OnStart(Flow f)
        {
            _blueprintCounter = BlueprintUtils.TryGetBlueprintCounter(counterName.value.Trim());
            OnCounterValueChanged += CounterValueChanged;
        }

        private void CounterValueChanged(string cName, int count)
        {
            if (cName == counterName.value.Trim())
            {
                onUpdate.Call(new Flow());
                if (count >= triggerValue.value)
                {
                    onEnd.Call(new Flow());
                }
            }
        }


        public override void OnPostGraphStoped()
        {
            _blueprintCounter = null;
            OnCounterValueChanged -= CounterValueChanged;
        }
    }
}